#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
COS上传/下载模块
负责从COS下载原图和上传处理结果
"""

import os
import logging
import requests
from qcloud_cos import CosConfig, CosS3Client
from config import Config

logger = logging.getLogger(__name__)

class COSHandler:
    def __init__(self):
        if not Config.COS_SECRET_ID or not Config.COS_SECRET_KEY:
            logger.warning("COS凭证未配置，COS功能将不可用")
            self.client = None
        else:
            self.config = CosConfig(
                Region=Config.COS_REGION,
                SecretId=Config.COS_SECRET_ID,
                SecretKey=Config.COS_SECRET_KEY,
                Scheme='https'
            )
            self.client = CosS3Client(self.config)
        self.bucket_name = Config.get_cos_bucket_name()
    
    def download_from_url(self, image_url: str, local_path: str) -> bool:
        """
        从COS URL下载图片到本地
        
        Args:
            image_url: COS图片URL（可以是COS直接URL或CDN URL）
            local_path: 本地保存路径
            
        Returns:
            bool: 下载是否成功
        """
        try:
            logger.info(f"开始从COS下载图片: {image_url}")
            
            # 下载图片（支持内网和公网URL）
            response = requests.get(image_url, timeout=30)
            response.raise_for_status()
            
            # 保存到本地
            os.makedirs(os.path.dirname(local_path), exist_ok=True)
            with open(local_path, 'wb') as f:
                f.write(response.content)
            
            file_size = os.path.getsize(local_path)
            logger.info(f"图片下载成功: {local_path}, 大小: {file_size / 1024:.2f} KB")
            return True
            
        except Exception as e:
            logger.error(f"从COS下载图片失败: {e}")
            return False
    
    def upload_file(self, local_path: str, task_id: str) -> str:
        """
        上传处理结果到COS
        
        Args:
            local_path: 本地文件路径
            task_id: 任务ID
            
        Returns:
            str: COS/CDN URL，失败返回None
        """
        if not self.client:
            logger.error("COS客户端未初始化，无法上传")
            return None
            
        try:
            # 生成COS对象key
            file_ext = os.path.splitext(local_path)[1]
            cos_key = f"enhanced/{task_id}{file_ext}"
            
            logger.info(f"开始上传到COS: {cos_key}")
            
            # 上传文件
            with open(local_path, 'rb') as f:
                self.client.put_object(
                    Bucket=self.bucket_name,
                    Body=f,
                    Key=cos_key,
                    EnableMD5=False
                )
            
            # 生成CDN URL
            cdn_url = f"https://{Config.CDN_DOMAIN}/{cos_key}"
            logger.info(f"上传成功: {cdn_url}")
            
            return cdn_url
            
        except Exception as e:
            logger.error(f"上传到COS失败: {e}")
            return None

# 全局实例
cos_handler = COSHandler()

